package com.syq.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.syq.pojo.Customer;
import com.syq.service.CustomerService;
import com.syq.service.impl.CustomerServiceImpl;
import com.syq.utils.R;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.repository.query.Param;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: CustomerController
 * @Description: TODO
 * @Create by: syq
 * @Date: 2022/8/16 16:15
 */

@RestController
@RequestMapping("/sys/customer")
@CrossOrigin
public class CustomerController {
    private ObjectMapper objectMapper = new ObjectMapper();
    private SearchRequest searchRequest;
    private SearchSourceBuilder sourceBuilder;
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private CustomerServiceImpl customerService;

    @GetMapping("/table")
    public R table(@RequestParam(defaultValue = "0") Integer page,
                   @RequestParam(defaultValue = "10") Integer limit,
                   @RequestParam(defaultValue = "1") Integer state,
                   String name) {
        searchRequest = new SearchRequest();
        searchRequest.indices("openapi_customer");
        sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder bool = new BoolQueryBuilder();
        bool.must(QueryBuilders.matchAllQuery());
        if (!StringUtils.isEmpty(state)) {
            bool.must(QueryBuilders.termQuery("state", state));
        }
        if (!StringUtils.isEmpty(name)) {
            bool.must(QueryBuilders.matchQuery("username", name));
        }
        sourceBuilder.from(page - 1);
        sourceBuilder.size(limit);
        sourceBuilder.query(bool);
        searchRequest.source(sourceBuilder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SearchHit[] hits = response.getHits().getHits();
        List<Customer> customerList = Arrays.stream(hits).map(hit -> {
            try {
                return objectMapper.readValue(hit.getSourceAsString(), Customer.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());
        return new R(customerList, 0, "查询成功");
    }

    @PostMapping("/add")
    public R add(Customer customer) throws Exception {
        Integer i = customerService.add(customer);
        Integer id = customer.getId();
        String json = objectMapper.writeValueAsString(customer);
        IndexRequest indexRequest = new IndexRequest("openapi_customer");
        indexRequest.id(String.valueOf(customer.getId()));
        indexRequest.source(json, XContentType.JSON);
        client.index(indexRequest, RequestOptions.DEFAULT);
        return new R(null, 0, "添加成功");
    }

    @PostMapping("/update")
    public R update(Customer customer) throws Exception {
        customerService.update(customer);
        String json = objectMapper.writeValueAsString(customer);
        UpdateRequest updateRequest = new UpdateRequest("openapi_customer", String.valueOf(customer.getId()));
        updateRequest.doc(json, XContentType.JSON);
        client.update(updateRequest, RequestOptions.DEFAULT);
        return new R(null, 0, "修改成功");
    }

    @PostMapping("/del")
    public R del(Integer[] ids) {
        BulkRequest bulkRequest = new BulkRequest();
        DeleteRequest deleteRequest = new DeleteRequest();
        Arrays.stream(ids).forEach(id -> {
            bulkRequest.add(new DeleteRequest("openapi_customer", String.valueOf(id)));
        });
        try {
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Integer> idList = Arrays.stream(ids).collect(Collectors.toList());
        customerService.del(idList);
        return new R(null, 0, "删除成功");
    }
}
